package com.stack.knowyouservice.service.impl;

import com.stack.knowyoubean.bean.User;
import com.stack.knowyoudao.dao.UserDao;
import com.stack.knowyouservice.service.EmailSendService;
import com.stack.knowyoubase.util.EmailUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

/**
 * 邮件发送
 *
 * @author stack
 */
@Service
@Scope("singleton")
public class EmailSendServiceImpl implements EmailSendService {

    @Resource
    private EmailUtil emailUtil;
    @Resource
    private UserDao userDao;


    @Override
    public String sendRegisterCaptCha(String mailTarget) throws Exception {
        User userByEmail = userDao.findUserByEmail(mailTarget);
        if (userByEmail != null) {
            return null;
        }
        String captcha = emailUtil.createCaptcha();
        String registerTitle = "知你注册验证码";
        emailUtil.sendCaptchaEmail(registerTitle, mailTarget, captcha);
        return captcha;
    }

    @Override
    public String sendForgetCaptCha(String username) throws Exception {
        User user = userDao.findUserByEmail(username);
        String forgetPassTitle = "知你忘记密码验证码";
        if (user == null) {
            //账号不存在
            try {
                Integer userId = Integer.parseInt(username);
                user = userDao.findUserById(userId);
            } catch (Exception e) {
                return null;
            }
            if (user == null) {
                return null;
            } else {
                String captcha = emailUtil.createCaptcha();
                emailUtil.sendCaptchaEmail(forgetPassTitle, user.getEmail(), captcha);
                return captcha;
            }
        } else {
            String captcha = emailUtil.createCaptcha();
            emailUtil.sendCaptchaEmail(forgetPassTitle, user.getEmail(), captcha);
            return captcha;
        }
    }
}
